package com.tct.worktimeboard.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tct.worktimeboard.entity.GroupType;
import com.tct.worktimeboard.mapper.GroupTypeMapper;
import com.tct.worktimeboard.service.IGroupTypeService;
import com.tct.worktimeboard.util.JsonUtil;
import com.tct.worktimeboard.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Huhailong
 * @Description
 * @Date 2021/2/23.
 */
@Slf4j
@Service
public class GroupTypeServiceImpl extends ServiceImpl<GroupTypeMapper, GroupType> implements IGroupTypeService {

    @Resource
    GroupTypeMapper groupTypeMapper;

    /**
     * 添加群组分类
     * @param groupType 群组分类信息
     * @return 返回添加状体
     */
    @Override
    public JSONObject addGroupType(GroupType groupType) {
        groupType.setCreateTime(TimeUtil.getDateTime());
        groupTypeMapper.insert(groupType);
        return JsonUtil.toJsonData();
    }

    /**
     * 通过KindCode 获取对应部门或BU的层级结构
     * @param kindCode dept or bu
     * @return 返回data
     */
    @Override
    public JSONObject getGroupType(String kindCode) {
        List<GroupType> childs = groupTypeMapper.selectList(new QueryWrapper<GroupType>().eq("kind_code",kindCode));
        Map<Long, List<GroupType>> map = childs.stream().collect(Collectors.groupingBy(GroupType::getParentId));
        List<GroupType> parent = map.get(0L);
        listNodes(parent,map);
        return JsonUtil.toJsonData(parent);
    }

    private void listNodes(List<GroupType> parent, Map<Long, List<GroupType>> map) {
        parent.forEach(groupType -> {
            List<GroupType> childs = map.get(groupType.getId());
            groupType.setChildren(childs);
            if(childs != null){
                listNodes(childs,map);
            }
        });
    }

    @Override
    public JSONObject getGroupTypeList(GroupType groupType) {
        QueryWrapper<GroupType> queryWrapper = new QueryWrapper<>();
        if(groupType.getKindName() != null && !groupType.getKindName().isEmpty()){
            queryWrapper.like("kind_name", groupType.getKindName());
        }
        if(!groupType.isPaged()) {groupType.setPageNum(1); groupType.setPageSize(10);}
        Page<GroupType> page = new Page<>(groupType.getPageNum(), groupType.getPageSize());
        return JsonUtil.toJsonData(groupTypeMapper.selectPage(page,queryWrapper));
    }
}
